import { Injectable } from '@angular/core';
// tslint:disable-next-line:import-blacklist
import { Observable } from 'rxjs';

@Injectable()
export class WebSocketService {
    ws: WebSocket;
    constructor() { }

    createObservableSocket(url: string): Observable<any> {
        this.ws = new WebSocket(url);
        return new Observable(
            observable => {
                this.ws.onopen = (event) => observable.next(event);
                this.ws.onmessage = (event) => observable.next(event);
                this.ws.onerror = (event) => observable.error(event);
                this.ws.onclose = (event) => observable.complete();
            }
        );
    }

    sendMessages(msg) {
        this.ws.send(msg);
    }

    closeWebSocket() {
        this.ws.close();
    }
}
